package com.common.baselibrary.request;


import android.util.Log;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator QQ:316854001
 * @name azh
 * @class name：com.cpic.team.azh.utils.request
 * @class describe
 * @time 2019/6/17 11:59
 * @change
 * @chang time
 * @class describe
 */
public abstract class RequestCallBack<T extends BaseCallModel> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        try {
            if (response.raw().code() == 200) {//200是服务器有合理响应
                int code = response.body().code;
                Log.e("网络==", response.body().getData() + "");
                if (code == 101) {
                    onSuccess(response.body());
                } else {
                    onFail(response.body().getMsg());
                }
            } else {//失败响应
                String s = response.errorBody().byteStream().toString();
                onFailure(call, new RuntimeException(s));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {//网络问题走该回调
        //根据自己的需求可以去定义多种的错误方式，响应多种的操作
        if (t instanceof SocketTimeoutException) {
            //
            onError(t.getMessage());
        } else if (t instanceof ConnectException) {
            //
            onError(t.getMessage());
        } else if (t instanceof RuntimeException) {
            onError(t.getMessage());
        } else {
            onError(t.getMessage());
        }
    }

    protected abstract void onError(String message);

    protected abstract void onSuccess(T response);

    protected abstract void onFail(String message);
}
